<template>
  <div class="search">
    <form action="/">
  <van-search
      class="fix"
      v-model="searchTxt"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
    />
    <!-- 三个组件 -->
    <!-- 搜索结果 -->
    <searchResult v-if="isshowResults" :search_txt="searchTxt"></searchResult>
    <!-- 搜索历史 -->
    <searchHistory @removeAllHistory="removeHistory" v-else-if="!searchTxt" :historys="historys"></searchHistory>
    <!-- 搜索建议 -->
    <searchSuggestion v-else :search_txt="searchTxt" @search="onSearch"></searchSuggestion>
  </form>
  </div>
</template>

<script>
import searchSuggestion from '@/views/search/components/searchSuggestion'
import searchHistory from '@/views/search/components/searchHistory'
import searchResult from '@/views/search/components/searchResult'
import { getUserHistorys } from '@/api/search/history.js'
export default {
  name: 'search',
  data () {
    return {
      searchTxt: '',
      isshowResults: false,
      historys: []
    }
  },
  components: {
    searchSuggestion,
    searchHistory,
    searchResult
  },
  created () {
    this.getUserHistory()
  },

  methods: {
    onSearch (val) {
      this.searchTxt = val
      // 当点击搜索的时候，就让搜索结果的list列表显示
      this.isshowResults = true
      // 发起请求之后，就往历史记录添加搜索历史
      if (val.trim() !== '') {
        const index = this.historys.indexOf(val)
        if (index === -1) {
          this.historys.unshift(val)
        }
      }
    },
    onCancel () {
      this.isshowResults = false
      console.log('取消')
    },
    // 开局获取用户的后台历史记录
    async getUserHistory () {
      try {
        const { data: res } = await getUserHistorys()
        console.log(res.data.keywords)
        this.historys = res.data.keywords
      } catch (err) {
        this.$toast.fail('获取历史记录失败！')
      }
    },
    // 删除全部历史记录
    removeHistory () {
      this.$dialog.confirm({
        message: '确认删除历史记录吗？'
      })
        .then(() => {
          this.historys = []
        })
        .catch(() => {
          return false
        })
    }
  }
}
</script>

<style scoped lang='less'>
.search {
  .van-search {
    height: 128px;
    background-color: rgb(0, 183, 255);
  }
  .fix {
    position:sticky;
    top: 0;
    z-index:999;
  }
}
</style>
